package cn.itrip.auth.controller;


import cn.itrip.auth.exception.SMSException;
import cn.itrip.auth.service.ItripUserService;
import cn.itrip.auth.service.TokenService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.beans.vo.userinfo.ItripUserVO;
import cn.itrip.common.*;
import com.fasterxml.jackson.core.JsonProcessingException;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Tequila
 **/
@CrossOrigin
@RestController
@RequestMapping("/auth/api")
public class UserController {

    @Autowired
    private ItripUserService itripUserService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private TokenService tokenService;

    @GetMapping("/logout")
    public Dto logout(HttpServletRequest request){
        String token = request.getHeader("token");
        String itripUserStr = (String) redisUtils.get(token);
        if (EmptyUtils.isNotEmpty(itripUserStr)){
            redisUtils.delete(token);
        }
        return DtoUtil.returnSuccess();
    }

    @PostMapping("/dologin")
    public Dto doLogin(@RequestParam String name, @RequestParam String password, HttpServletRequest request){


        // 生成token

        // 去数据库查询用户对象
        if (EmptyUtils.isNotEmpty(name) && EmptyUtils.isNotEmpty(password)){
           ItripUser itripUser =  itripUserService.doLogin(name, MD5.getMd5(password,32));
           if (EmptyUtils.isNotEmpty(itripUser)){

               //   知道是移动端还是pc端
               String userAgent = request.getHeader("user-agent");
               // 生成token
               String token = tokenService.getToken(userAgent,itripUser);
               // TODO 存储到redis中2个小时
               ObjectMapper objectMapper = new ObjectMapper();
               try {
                   redisUtils.putValue(token,objectMapper.writeValueAsString(itripUser),60*60*2);
               } catch (JsonProcessingException e) {
                   e.printStackTrace();
                   return DtoUtil.returnFail("redis存储错误",ErrorCode.AUTH_REDIS_ERROR);
               }
               // 返回vo  itripTokenVo
               ItripTokenVO tokenVO = new ItripTokenVO();
               tokenVO.setToken(token);
               // key: token:PC-USERCODE[加密]-USERID-CREATIONDATE-RONDEM[6 位]
               String createTokenDate = token.split("-")[3];

               try {
                   Date genDate = new SimpleDateFormat("yyyyMMddHHmmss").parse(createTokenDate);
                   long time = genDate.getTime();
                   tokenVO.setGenTime(time);
                   // 两个小时  ==
                   tokenVO.setExpTime(time+(60*60*2*1000));

               } catch (ParseException e) {
                   e.printStackTrace();
                   return DtoUtil.returnFail("时间转换失败",ErrorCode.DATE_ERROR);
               }
               return DtoUtil.returnDataSuccess(tokenVO);
           }else{
               return DtoUtil.returnFail("用户名或者密码错误!",ErrorCode.AUTH_PARAMETER_ERROR);
           }


        }

        return null;
    }

    @PutMapping("/validatephone")
    public Dto validatePhone(@RequestParam String code,@RequestParam String user){

        try {
            if (EmptyUtils.isNotEmpty(code) && EmptyUtils.isNotEmpty(user)){

                if(itripUserService.validatePhone(code,user)){
                    return DtoUtil.returnSuccess();
                }else{
                    return DtoUtil.returnFail("验证码错误",ErrorCode.AUTH_AUTHENTICATION_FAILED);
                }
            }else{
                return DtoUtil.returnFail("手机号或者验证码不能为空",ErrorCode.PARAM_ISNULL);
            }
        }catch (JsonProcessingException e){
            e.printStackTrace();
            return DtoUtil.returnFail("json转换错误",ErrorCode.AUTH_JSON_ERROR);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统错误",ErrorCode.SYSTEM_ERROR);
        }
    }

    @PostMapping("/registerbyphone")
    public Dto registerByPhone(@RequestBody ItripUserVO itripUserVO){

        try {
            if (EmptyUtils.isNotEmpty(itripUserVO.getUserCode())) {

                boolean result = itripUserService.registerByPhone(itripUserVO);

                return DtoUtil.returnSuccess();

            } else {
                return DtoUtil.returnFail("手机号不能为空", ErrorCode.PARAM_ISNULL);
            }
        }catch (SMSException e){
            e.printStackTrace();
            return DtoUtil.returnFail("短信发送失败:"+e.getMessage(),ErrorCode.AUTH_SMS_ERROR);
        }catch (JsonProcessingException e){
            e.printStackTrace();
            return DtoUtil.returnFail("json转换错误",ErrorCode.AUTH_JSON_ERROR);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统错误",ErrorCode.SYSTEM_ERROR);
        }


    }

    @PutMapping("/activate")
    public Dto activate(@RequestParam String code,@RequestParam String user ){
        // 1.验证code是否正确
        String redisMailCode = (String) redisUtils.get(user + "_mailCode");
        if (code.equals(redisMailCode)){
            // 2.去数据库修改激活状态
             if(itripUserService.activate(user)){
                 return DtoUtil.returnSuccess();
             }else{
                 return DtoUtil.returnFail("数据库激活失败!",ErrorCode.AUTH_ACTIVATE_FAILED);
             }
        }else{
            return DtoUtil.returnFail("验证码错误!",ErrorCode.AUTH_ACTIVATE_FAILED);
        }
    }

    @PostMapping("/doregister")
    public Dto doRegister(@RequestBody ItripUserVO itripUserVO){

        try {
            if (EmptyUtils.isNotEmpty(itripUserVO.getUserCode()) &&
                EmptyUtils.isNotEmpty(itripUserVO.getUserName()) &&
                EmptyUtils.isNotEmpty(itripUserVO.getUserPassword())
            ) {
                if(itripUserService.doRegister(itripUserVO)){
                    return DtoUtil.returnSuccess();
                }else{
                    return DtoUtil.returnFail("注册失败",ErrorCode.SYSTEM_ERROR);
                }
            } else {
                return DtoUtil.returnFail("用户名或者密码或者邮箱不能为空",ErrorCode.PARAM_ISNULL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统错误",ErrorCode.SYSTEM_ERROR);
        }
    }

    @GetMapping("/ckusr")
    public Dto ckUsr(@RequestParam String name){

        try {
            if (EmptyUtils.isNotEmpty(name)) {
                if(itripUserService.ckUsr(name)){
                    return DtoUtil.returnFail("此用户名已经被使用!", ErrorCode.AUTH_USER_ALREADY_EXISTS);

                }else{
                    return DtoUtil.returnSuccess("此用户名可以使用");
                }
            } else {
                return DtoUtil.returnFail("用户名不能为空",ErrorCode.PARAM_ISNULL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统错误",ErrorCode.SYSTEM_ERROR);
        }
    }


}
